package top.frsf.panel;

import top.frsf.context.StarterContext;
import top.frsf.enums.GameStateEnum;
import top.frsf.input.MouseAction;
import top.frsf.music.SimpleMusicPlayer;

import javax.swing.*;
import java.awt.*;

import static top.frsf.utils.ConfigLoader.getInt;
import static top.frsf.utils.ConfigLoader.getString;

/**
 * @author FRSF
 * @since 2025/8/1 10:02
 */
public class GamePanel extends JFrame {
    /* 配置文件参数 */
    private final int width = getInt("game.width");
    private final int height = getInt("game.height");
    private final String title = getString("game.title");
    private final String musicPath = getString("music.path");
    private final int musicVolume = getInt("music.volume");
    private final int fps = getInt("repaint.fps");

    /* 全局游戏状态 */
    public static GameStateEnum state = GameStateEnum.HOME;

    /* 场景启动器上下文 */
    public static StarterContext starterContext = new StarterContext();

    @Override
    public void paint(Graphics graphics) {
        // 双缓存机制，新Image绘制完成之后，再显示到屏幕上，避免clean and paint闪烁问题
        Image flashImage = this.createImage(width, height);
        Graphics g = flashImage.getGraphics();

        // 场景上下文启动器启动
        starterContext.run(g);

        // 绘制替换
        graphics.drawImage(flashImage, 0, 0, null);
    }

    public void launch() {
        /* 背景音乐初始化 */
        musicInit();
        /* 鼠标事件初始化 */
        mouseInit();
        /* 窗体初始化 */
        windowsInit();
        /* 游戏启动 */
        startGame();
    }

    private void musicInit() {
        SimpleMusicPlayer player = new SimpleMusicPlayer(musicPath, musicVolume);
        player.createAndStartThread();
    }

    private void mouseInit() {
        MouseAction mouseEvent = new MouseAction();
        // 添加鼠标点击监听
        this.addMouseListener(mouseEvent);
        // 添加鼠标移动监听
        this.addMouseMotionListener(mouseEvent);
    }

    private void windowsInit() {
        this.setSize(width, height);
        this.setTitle(title);
        // 相对位置居中
        this.setLocationRelativeTo(null);
        // 关闭窗体逻辑
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 窗体可见
        this.setVisible(true);
        // 窗体不可拉伸
        this.setResizable(false);
    }

    private void startGame() {
        // 重绘延时计算
        int delay = 1000 / fps;
        // 定时器
        Timer gameTimer = new Timer(delay, e -> repaint());
        gameTimer.start();
    }
}
